App = {};
var path = 'rest/comisarias';

App.ComisariaModel = Backbone.Model.extend({
   urlRoot: path,
   idAttribute: 'gid',
   parent: null
});
App.ComisariaCollection = Backbone.Collection.extend({
   model: App.ComisariaModel,
   url: path
});
App.ComisariaView = Backbone.View.extend({
   tagName: 'div',
   events: {
      'click .comisaria-title': 'center_view'
   },
   template: _.template($('#comisaria-template').html()),
   render: function() {
      $('#west-tab-1-container').append(this.$el.html(this.template(this.model.toJSON())));
      return this;
   },
   center_view: function() {
      this.options.parent.message_broker({
         command: 'center_view',
         data: {
            lon: this.model.attributes.geometry.coordinates[0],
            lat: this.model.attributes.geometry.coordinates[1],
            id:  this.model.attributes.properties.id
         }
      });
   }
});

var path2 = 'rest/jurisdiccion';
App.JurisdiccionModel = Backbone.Model.extend({
   urlRoot: path2,
   idAttribute: 'id',
});
App.JurisdiccionCollection = Backbone.Collection.extend({
   model: App.JurisdiccionModel,
   url: path2
});

var path3 = 'rest/puntos';
App.PuntoModel = Backbone.Model.extend({
   urlRoot: path3,
   idAttribute: 'gid',
   parent: null
});
App.PuntoCollection = Backbone.Collection.extend({
   model: App.PuntoModel,
   url: path3
});

App.MapView = Backbone.View.extend({
   el: 'body',
   initialize: function() {
      this.render();
   },
   render: function() {
      var self = this;
      this.map = new OpenLayers.Map('main-map', {
         restrictedExtent: new OpenLayers.Bounds(-8628211.7516315, -1365356.4175522, -8523798.7710085, -1338527.0206278),
         theme: null
      });
      this.map.addControls([new OpenLayers.Control.Navigation()]);
      this.baselayer = new OpenLayers.Layer.OSM("CloudMade", [
         "http://a.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/22677/256/${z}/${x}/${y}.png",
         "http://b.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/22677/256/${z}/${x}/${y}.png",
         "http://c.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/22677/256/${z}/${x}/${y}.png"],
         {
            isBaseLayer: true,
            tileOptions: {crossOriginKeyword: null}
         }
      );
      this.map.addLayer(this.baselayer);

      
      /* Points */
      var points_context = {
         getColor: function(feature) {
            switch (feature.attributes.properties.type) {
               case 'red':
                  return 'http://127.0.0.1/icon.red.fw.png';
                  break;
               case 'blue':
                  return 'http://127.0.0.1/icon.blue.fw.png';
                  break;
               case 'green':
                  return 'http://127.0.0.1/icon.green.fw.png';
                  break;                  
            }
            return '#ff0000';
         }
      };
      
      var points_template = {
         //'pointRadius': 10,
         externalGraphic: "${getColor}",
         graphicWidth: 25,
         graphicHeight: 25,
         fillOpacity: 1
      };
     
      var points_style = new OpenLayers.Style( points_template, {context: points_context });
      var points_stylemap = new OpenLayers.StyleMap(points_style);

      this.points_layer = new OpenLayers.Layer.Vector('Points', {
         styleMap: points_stylemap,
         maxResolution: 18
      });
      this.map.addLayer(this.points_layer);
      
      this.pointc_layer = new OpenLayers.Layer.Vector("Point");
      this.map.addLayer(this.pointc_layer);
      
      this.point_control = new OpenLayers.Control.DrawFeature(
         this.pointc_layer,
         OpenLayers.Handler.Point,
         {
            featureAdded: function(e) {
               var wkt = new OpenLayers.Format.WKT;
               self.create_punto(wkt.write(e));
            }
         }
      );
      this.map.addControl(this.point_control);
      
      
      /* End Points */ 
      
      this.jurisdiccion_layer = new OpenLayers.Layer.Vector('Jurisdicción', {
         maxResolution: 23
      });
      this.map.addLayer(this.jurisdiccion_layer);
      
      this.polygon_layer = new OpenLayers.Layer.Vector("Polygon");
      this.map.addLayer(this.polygon_layer);
      this.polygon_control = new OpenLayers.Control.DrawFeature(
         this.polygon_layer,
         OpenLayers.Handler.Polygon,
         {
            featureAdded: function(e) {
               var wkt = new OpenLayers.Format.WKT;
               self.create_jurisdiccion(wkt.write(e));
            }
         }
      );
      this.map.addControl(this.polygon_control);
      
      var comisaria_style = new OpenLayers.Style({
         //'pointRadius': 10,
         externalGraphic: "http://127.0.0.1/icon.fw.png",
         graphicWidth: 25,
         graphicHeight: 25,
         fillOpacity: 1
      });
      var comisaria_stylemap = new OpenLayers.StyleMap({
         default: comisaria_style
      });
      this.comisaria_layer = new OpenLayers.Layer.Vector('Puntos', {
         styleMap: comisaria_stylemap,
         maxResolution: 20
      });
      this.map.addLayer(this.comisaria_layer);
      
      this.map.setCenter (new OpenLayers.LonLat(-8576005.26132, -1351941.71909), 11);
   },
   create_jurisdiccion: function(data) {
      this.options.parent.message_broker({
         command: 'add_jurisdiccion',
         data: data
      });
   },
   create_punto: function(data) {
      this.options.parent.message_broker({
         command: 'add_punto',
         data: data
      });
   },
   add_comisaria: function(data) {
      var point = new OpenLayers.Geometry.Point(data.attributes.center.lon, data.attributes.center.lat);
      var attributes = data.attributes
      this.comisaria_layer.addFeatures([new OpenLayers.Feature.Vector(point, attributes)]);

   },
   add_punto: function(data) {
      var point = new OpenLayers.Geometry.Point(data.attributes.center.lon, data.attributes.center.lat);
      var attributes = data.attributes
      this.points_layer.addFeatures([new OpenLayers.Feature.Vector(point, attributes)]);
      this.points_layer.refresh();
   },
   add_jurisdiccion: function(data) {
      var points = new Array;
      _.each(data.attributes.geometry.coordinates[0], function(value, key, list){
         points.push(new OpenLayers.Geometry.Point(value[0], value[1]));
      })
      var ring = new OpenLayers.Geometry.LinearRing(points);
      var polygon = new OpenLayers.Geometry.Polygon([ring]);
      var feature = new OpenLayers.Feature.Vector(polygon);
      this.jurisdiccion_layer.addFeatures([feature]);
   },
   set_center: function(lon, lat) {
      this.map.setCenter(new OpenLayers.LonLat(lon, lat), 15);
   },
   polygon_control_set: function(value) {
      if (value) {
         this.polygon_control.activate();
      }
      else {
         this.polygon_control.deactivate();
      }
   },
   point_control_set: function(value) {
      if (value) {
         this.point_control.activate();
      }
      else {
         this.point_control.deactivate();
      }      
   }
});
App.LayoutView = Backbone.View.extend({
   el: 'body',
   events: {},
   initialize: function() {
      this.render();
   },
   render: function() {
      $('body').layout({
         applyDefaultStyles: false,
         west__size: 68,
         west__closable: false,
         west__resizable: false,
         west__slidable: false,
         west__spacing_open: 0,
         west__spacing_closed: 0
      });
   },
   resize: function() {
   }
});
App.MenuView = Backbone.View.extend({
   el: 'body',
   events: {},
   initialize: function() {
      this.render();
      this._resize();    
   },
   resize: function(val) {
      $('#main-menu-container > .box').height($('#main-menu-container').height()-10);
      $('#west-tab-1').height($('#main-menu-container').height()-20);
      $('#tab-1-superpanel').height($('#main-menu-container').height()-20);
      $('#tab-1-superpanel').wijsuperpanel("refresh");
   },
   _resize: function(val) {
      $('#main-menu-container > .box').height($('#main-menu-container').height()-10);
      $('#west-tab-1').height($('#main-menu-container').height()-20);
      $('#tab-1-superpanel').height($('#main-menu-container').height()-20);
   },
   render: function() {
      $('#main-menu-tabs').wijtabs({alignment: 'bottom'});
      $('#tab-1-superpanel').wijsuperpanel({
         autoRefresh: false,
         showRounder: false,
         hScroller: {
            scrollMode: 'none'
         }
      });
   }
});

App.MainView = Backbone.View.extend({
   el: 'body',
   type: 'red',
   events: {
      'click #left-sidebar > button': 'create_point'
   },
   create_point: function(e) {
      console.log($(e.currentTarget).attr('rel'));
      this.type = $(e.currentTarget).attr('rel');
      this.map.point_control_set(true);
   },
   initialize: function() {
      this.t = -1;
      var self = this;
      $(window).bind('resize.app', _.bind(self.resize, self));
      this.comisarias = new App.ComisariaCollection;
      this.jurisdicciones = new App.JurisdiccionCollection;
      this.puntos = new App.PuntoCollection;
      this.render();
   },
   load_data: function() {
      var self = this;
      //this.comisarias.fetch({async: false});
      this.comisarias.fetch({
         success: function(collection, response) {
            collection.each(function(comisaria) {
               self.map.add_comisaria(comisaria);
               var element = new App.ComisariaView({model: comisaria, parent: self});
               element.render();
            });
            self.menu.resize();
         }
      });
      this.jurisdicciones.fetch({
         success: function(collection, response) {
            collection.each(function(jurisdiccion) {
               self.map.add_jurisdiccion(jurisdiccion);
            });
         }
      });
      this.puntos.fetch({
         success: function(collection, response) {
            collection.each(function(punto) {
               self.map.add_punto(punto);
            });
         }
      });
   },
   load_point_data: function() {
      var self = this;
      this.map.pointc_layer.removeAllFeatures();
      this.map.points_layer.removeAllFeatures();
      this.puntos.fetch({
         reset: true,
         success: function(collection, response) {
            collection.each(function(punto) {
               self.map.add_punto(punto);
               
            });
            self.map.points_layer.refresh();
         }
      });
      this.map.points_layer.refresh();
   },
   message_broker: function(message) {
      var self = this;
      switch (message.command) {
         case 'center_view':
            this.map.set_center(message.data.lon, message.data.lat);
            this.map.polygon_control_set(true);
            this.comisaria_id = message.data.id;
            console.log(message.data);
            break;
         case 'add_jurisdiccion':
            console.log(self.comisaria_id);
            var new_jurisdiccion = new App.JurisdiccionModel({
               data: message.data,
               comisaria_id: self.comisaria_id
            });
            new_jurisdiccion.save();
            this.map.polygon_control_set(false);
            break;
         case 'add_punto':
            console.log(self.type);
            var new_punto = new App.PuntoModel({
               data: message.data,
               type: self.type
            } );
            new_punto.save();
            this.map.point_control_set(false);
            this.load_point_data();
            break;
      }
   },

   resize: function() {
      var self = this;
      clearTimeout(this.t);
      this.layout.resize();
      this.menu.resize();
      this.t = setTimeout(this.menu.resize, 250);
   },
   render: function() {
      var self = this;
      this.layout = new App.LayoutView();
      this.map    = new App.MapView({ parent: self });
      this.menu   = new App.MenuView();
      $('#left-sidebar > button').button({});
      this.load_data();
   }
});
var Application = new App.MainView();


